package com.lzht.games.access.handler;

import com.alibaba.fastjson.JSONObject;
import com.lzht.games.access.cache.SessionCache;
import com.lzht.games.access.protocol.BasicErrorResp;
import com.lzht.games.access.stream.SendService;
import com.lzht.games.access.util.SessionUtil;
import com.lzht.games.common.common.NotifyMsg;
import com.lzht.games.common.common.ResponseMsg;
import com.lzht.games.common.constant.ModuleConstant;
import com.lzht.games.common.header.NotifyHeader;
import com.lzht.games.common.header.ReqHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Create by weishuaiding on 2018/8/31 17:44
 */
public class WebSocketController extends TextWebSocketHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private SendService sendService;
    @Value("${spring.cloud.stream.bindings.input.destination}")
    private String accessId;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        logger.info("receive new message: {}, sessionId: {}", message.getPayload(), session.getId());

        String jsonReq = message.getPayload();
        if (jsonReq == null) {
            ResponseMsg resp = new ResponseMsg();
            SessionUtil.sendMessage(session.getId(), resp.paramError(new BasicErrorResp(), null));
            return;
        }

        JSONObject object = JSONObject.parseObject(jsonReq);
        ReqHeader header = object.getObject("header", ReqHeader.class);

        String uuid = SessionCache.getSessionUUid(session.getId());
        if (header.getModuleId() == ModuleConstant.MODULE_ACCESS
                && header.getMsgCode() == 10003) {
            //心跳检测
            SessionUtil.sendMessage(uuid, object.toJSONString());
            return;
        }

        NotifyHeader notifyHeader = new NotifyHeader(accessId, uuid);
        NotifyMsg<JSONObject> notify = new NotifyMsg<>();
        notify.setHeader(notifyHeader);
        notify.setNotifyData(object);

        int moduleId = header.getModuleId();
        if (moduleId == ModuleConstant.MODULE_USER) {
            sendService.notifyUser(notify);
        } else if (moduleId == ModuleConstant.MODULE_ROOM) {
            sendService.notifyRoom(notify);
        } else {
            ResponseMsg resp = new ResponseMsg();
            SessionUtil.sendMessage(session.getId(), resp.paramError(new BasicErrorResp(), null));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.info("Session ID={} close...", session.getId());

        String uuid = SessionCache.getSessionUUid(session.getId());
        sendService.notifyOffLine(uuid);
        SessionCache.removeSession(session.getId());
        super.afterConnectionClosed(session, status);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("Session ID={} open succeed !", session.getId());
        SessionCache.addSession(session.getId(), session);
        super.afterConnectionEstablished(session);
    }
}
